package com.fjp.heartguard.ui.home

import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.View
import coil.load
import coil.transform.RoundedCornersTransformation
import com.fjp.heartguard.R
import com.fjp.heartguard.app.App
import com.fjp.heartguard.app.base.BaseFragment
import com.fjp.heartguard.app.data.bean.AccountState
import com.fjp.heartguard.app.data.bean.AppVersion
import com.fjp.heartguard.app.data.bean.SelfEdit
import com.fjp.heartguard.app.data.bean.State
import com.fjp.heartguard.app.eventViewModel
import com.fjp.heartguard.app.ext.showToast
import com.fjp.heartguard.app.util.AppUtils
import com.fjp.heartguard.app.weight.pop.AssessmentNoticePop
import com.fjp.heartguard.app.weight.pop.UpdateVersionPop
import com.fjp.heartguard.databinding.FragmentHomeBinding
import com.fjp.heartguard.ui.message.MessageActivity
import com.fjp.heartguard.ui.question.RecordActivity
import com.fjp.heartguard.ui.userinfo.UserinfoActivity
import com.fjp.heartguard.viewmodel.HomeViewModel
import com.heartguard.appupdate.utils.ApkUtils
import com.lxj.xpopup.XPopup
import me.hgj.jetpackmvvm.base.appContext
import me.hgj.jetpackmvvm.ext.parseState
import me.hgj.jetpackmvvm.ext.util.dp2px
import java.io.File


class HomeFragment : BaseFragment<HomeViewModel, FragmentHomeBinding>(), UpdateVersionPop.InstallClickListener {
    var accountState: AccountState? = null
    lateinit var appVersion: AppVersion
    override fun initView(savedInstanceState: Bundle?) {
        mDatabind.viewModel = mViewModel
        mDatabind.click = ClickProxy()
        mViewModel.getState(AppUtils.getAppVersionName(requireContext()))
        mDatabind.nameTv.text = "Hi,${if (App.userInfo.name.isEmpty()) App.userInfo.mobile else App.userInfo.name}"
        mDatabind.avatarIv.load(App.userInfo.profile, builder = {
            allowHardware(false)
            transformations(RoundedCornersTransformation(requireContext().dp2px(19).toFloat()))
        })
    }


    override fun createObserver() {
        super.createObserver()

        eventViewModel.userInfoChange.observeInFragment(this) {
            mDatabind.nameTv.text = App.userInfo.name
            mDatabind.avatarIv.load(App.userInfo.profile, builder = {
                allowHardware(false)
                transformations(RoundedCornersTransformation(requireContext().dp2px(19).toFloat()))
            })
            mViewModel.getState(AppUtils.getAppVersionName(requireContext()))
        }

        eventViewModel.unreadMessageEvent.observeInFragment(this) {
            if (it != 0) {
                mDatabind.messageIv.setBackgroundResource(R.drawable.home_message_tip)
            } else {
                mDatabind.messageIv.setBackgroundResource(R.drawable.home_message)
            }
        }

        mViewModel.accountState.observe(this) {
            parseState(it, {
                accountState = it
                App.accountState = it
                if (it.status == State.FORBIDDEN.value) {
                    //账号如果被锁定显示UI
                    mViewModel.hasMoreAction.set(true)
                    mDatabind.topIv.setBackgroundResource(R.drawable.bg_home_lock)
                    mDatabind.homeTitleTv.setText("您的账号已经被锁定请联系管理员解锁")
                    mDatabind.startTestBtn.isEnabled = false
                    mDatabind.cartonIv.setBackgroundResource(R.drawable.home_carton04)
                    mDatabind.singleBtn.setText("联系管理员")
                    mDatabind.singleBtn.setBackgroundResource(R.drawable.bg_btn_user_lock)

                } else if (it.new_version == 1) {
                    mDatabind.startTestBtn.isEnabled = true
                    if (!App.newVersionClickLater) {
                        mViewModel.hasMoreAction.set(true)
                        mDatabind.homeTitleTv.setText("有新版本可以升级快更新尝鲜吧！")
                        mDatabind.singleBtn.visibility = View.GONE
                        mDatabind.laterBtn.visibility = View.VISIBLE
                        mDatabind.updateBtn.visibility = View.VISIBLE
                        mViewModel.checkVersion()
                    }
                } else if (it.is_self_edit == SelfEdit.NO.value) {
                    mViewModel.hasMoreAction.set(true)
                    mDatabind.startTestBtn.isEnabled = false
                } else if (it.overdue_olders != 0) {
                    mDatabind.startTestBtn.isEnabled = true
                    mViewModel.hasMoreAction.set(true)
                    //  有几位老人未评估
                    mDatabind.homeTitleTv.setText("本月还有${it.overdue_olders}位老人尚未评估，请尽快安排")
                    mDatabind.singleBtn.setText("立即查看")
                    mDatabind.cartonIv.setBackgroundResource(R.drawable.home_carton02)
                } else {
                    mDatabind.startTestBtn.isEnabled = true
                    mViewModel.hasMoreAction.set(false)
                }
            })
        }
        mViewModel.appVersion.observe(this) {
            parseState(it, {
                appVersion = it
            })
        }
    }

    inner class ClickProxy {
        fun clickMessage() {
            startActivity(Intent(context, MessageActivity::class.java))
        }

        fun clickQuestion() {
            showAssessmentNoticePop()

        }

        fun clickSingleBtn() {
            if (accountState == null) {
                return
            }
            if (accountState?.is_self_edit == SelfEdit.NO.value) {
                startActivity(Intent(context, UserinfoActivity::class.java))
            } else if (accountState?.status == State.FORBIDDEN.value) {
                showLinkManagerPop()
            } else if (accountState?.overdue_olders != 0) {
                startActivity(Intent(context, MessageActivity::class.java))
            }
        }

        fun clickLater() {
            App.newVersionClickLater = true
            mViewModel.hasMoreAction.set(false)
        }

        fun clickUpdateVersion() {
            if (this@HomeFragment::appVersion.isInitialized) {
                showUpdateVersionPop()
            } else {
                appContext.showToast("版本更新数据获取失败")
            }
        }
    }

    fun showUpdateVersionPop() {
        XPopup.Builder(context).dismissOnTouchOutside(false).dismissOnBackPressed(false).asCustom(UpdateVersionPop(requireContext(), appVersion, this)).show()
    }

    fun showLinkManagerPop() {
        XPopup.Builder(context).asConfirm("管理员", "邮箱：qingxinshouhu@163.com", "取消", "复制", { callPhone() }, {
            val clipboard: ClipboardManager? = appContext.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager?
            val clip = ClipData.newPlainText("label", "要复制的文本内容")
            clipboard?.setPrimaryClip(clip)
            appContext.showToast("复制成功")
        }, false).show()
    }


    private fun callPhone() {
        val intent = Intent(Intent.ACTION_DIAL)
        intent.setData(Uri.parse("tel:15652631379"))
        startActivity(intent)

    }

    fun showAssessmentNoticePop() {
        context?.let {
            XPopup.Builder(context).dismissOnTouchOutside(false).dismissOnBackPressed(false).isDestroyOnDismiss(true).autoOpenSoftInput(false).asCustom(AssessmentNoticePop(it, object : AssessmentNoticePop.Listener {
                override fun onclickStart() {
                    startActivity(Intent(it, RecordActivity::class.java))
                }

            })).show()
        }

    }

    override fun onClick(file: File) {
        requireActivity().runOnUiThread {
            if (!requireContext().packageManager.canRequestPackageInstalls()) {
                App.apkFile = file
                ApkUtils.startPackageInstallActivity(requireActivity())
            } else {
                ApkUtils.installAPK(requireActivity(), file)
            }


        }

    }

}